package com.blackfish.server.job;

import com.blackfish.server.ShowcaseServerAioHandler;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.udp.UdpClient;
import org.tio.core.udp.UdpClientConf;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

public class UdpJob implements Job {
    public UdpJob(){
        UdpConf udpConf = new UdpConf();
        this.serverip = udpConf.getServerip();
        this.serverip = udpConf.getFindcliip();
    }
    public UdpClientConf udpClientConf = null;
    public UdpClient udpClient = null;
    public String serverip = "127.0.0.1";
    public String findcliip = "192.168.123.229";
    public String mask = "255.255.255.0";
    public boolean config = false;//new UdpConf();
    private static Logger log = LoggerFactory.getLogger(ShowcaseServerAioHandler.class);

    public void getMask(){
        for(int i=1;i<32;i++) {
            int ip = 0xFFFFFFFF << (32 - i);
            String binaryStr = Integer.toBinaryString(ip);
            StringBuffer buffer = new StringBuffer();
            for(int j=0;j<4;j++) {
                int beginIndex = j*8;
                buffer.append(Integer.parseInt(binaryStr.substring(beginIndex, beginIndex+8), 2)).append(".");
            }
            System.out.println("net mask "+i+" ,submask:"+buffer.substring(0,buffer.length()-1));

        }
    }

    void getHostIp(){

        // TODO 获取子网掩码
        try {
            InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
            String hostAddress = address.getHostAddress();//192.168.0.121
            serverip = hostAddress;
            String[] ip_list = hostAddress.split(".");
            ip_list[3] = "255";
            findcliip = String.join(".",ip_list);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }


    public void Config(){
        //getHostIp();
        UdpClientConf udpClientConf = new UdpClientConf(findcliip, 12000, 1000);
        udpClient = new UdpClient(udpClientConf);
        udpClient.start();
        config = true;
        // new UdpConf().setConf(true);
        //System.out.println("客户端初始化");
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            //这里写上你的业务代码
            config = new UdpConf().getConf();
            if(!config){
                this.Config();
            }

            udpClient.send(("{\"server_ip\":\""+ serverip +"\",\"server_port\":5678}").getBytes());
            //TimeUnit.MICROSECONDS.sleep(800);
            // System.out.println("开始UDP广播,搜寻客户端");

        } catch (Exception e) {
            //这里处理异常log.error(e.toString(), e);
            log.error("发送广播失败");
        }
    }
}
